package org.lilred.nzbberry.download;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.util.StringUtilities;

import org.lilred.nzbberry.http.HttpRequestDispatcher;
import org.lilred.nzbberry.webservice.SabnzbdClient;


public class NzbSwapper extends Thread {
	static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";
	protected HttpConnection nzbServerConnection; 
	String contentType;
	String filename;
	String boundaryMessage;
	String endBoundary;

	public NzbSwapper(HttpConnection nzbServerConnection) {
		this.nzbServerConnection = nzbServerConnection;
		try {
			contentType = nzbServerConnection.getHeaderField("Content-Type");
			String disposition = nzbServerConnection.getHeaderField("Content-Disposition");
			int start = disposition.indexOf("=") + 1;
			filename = disposition.substring(start);
			filename = StringUtilities.removeChars(filename, "\";");
			endBoundary = "\r\n--" + BOUNDARY + "--\r\n";
			boundaryMessage = getBoundaryMessage(BOUNDARY, new Hashtable(), "nzbfile", filename, contentType);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println(e.getMessage());
		}
	}


	public void run() {
		try {
			InputStream nzbServerInputStream = nzbServerConnection.openInputStream();
			byte[] buffer = new byte[20000];
			int bytesRead = nzbServerInputStream.read(buffer);
			ByteArrayOutputStream nzbServerOutputStream = new ByteArrayOutputStream();
			while (bytesRead > 0) {
				nzbServerOutputStream.write(buffer, 0, bytesRead);
				System.out.println(bytesRead);
				bytesRead = nzbServerInputStream.read(buffer);
			}
			nzbServerInputStream.close();
			nzbServerConnection.close();

			HttpConnection sabnzbdConnection;
			String sabnzbdUrl = SabnzbdClient.getApiUrl("addfile") + HttpRequestDispatcher.getConnectionParameters();
			sabnzbdConnection = (HttpConnection) Connector.open(sabnzbdUrl);
			sabnzbdConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
			sabnzbdConnection.setRequestMethod(HttpConnection.POST);
			OutputStream sabnzbdOutputStream = sabnzbdConnection.openOutputStream();
			byte[] postBytes = getPostBytes(nzbServerOutputStream.toByteArray());
			//System.out.println(new String(postBytes));
			sabnzbdOutputStream.write(postBytes);
			sabnzbdOutputStream.close();

			ByteArrayOutputStream sabnzbdInputStream = new ByteArrayOutputStream();
			InputStream is = sabnzbdConnection.openInputStream();
			int ch; 
			while ((ch = is.read()) != -1)
			{
				sabnzbdInputStream.write(ch);
			}
			byte[] res = sabnzbdInputStream.toByteArray();
			System.out.println(new String(res));
			sabnzbdConnection.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println(e.getMessage());
		}
	}

	String getBoundaryMessage(String boundary, Hashtable params, String fileField, String fileName, String fileType)
	{
		StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");
		Enumeration keys = params.keys();
		while(keys.hasMoreElements())
		{
			String key = (String)keys.nextElement();
			String value = (String)params.get(key);
			res.append("Content-Disposition: form-data; name=\"").append(key).append("\"\r\n")    
			.append("\r\n").append(value).append("\r\n")
			.append("--").append(boundary).append("\r\n");
		}
		res.append("Content-Disposition: form-data; name=\"").append(fileField).append("\"; filename=\"").append(fileName).append("\"\r\n") 
		.append("Content-Type: ").append(fileType).append("\r\n\r\n");
		return res.toString();
	}

	byte[] getPostBytes(byte[] fileBytes) {
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			bos.write(boundaryMessage.getBytes());
			bos.write(fileBytes);
			bos.write(endBoundary.getBytes());
			return bos.toByteArray();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return null;
	}

}